﻿using System;
using System.Diagnostics;
using System.Management;

namespace SearchInFiles.Lib.Tools
{
    public class CPUHelper:IDisposable
    {
        // 用于获得CPU信息
        PerformanceCounter[] counters;
        public CPUHelper()
        {

            // 初始化计数器
            counters = new PerformanceCounter[System.Environment.ProcessorCount];
            for (int i = 0; i < counters.Length; i++)
            {
                counters[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
                counters[i].NextValue(); // 这里是为了获得CPU占用率的值
            }
        }

        // 返回所有核心的CPU的占用率的值
        public double[] GetCPUUsage()
        {
            double[] info = new double[counters.Length];
            for (int i = 0; i < counters.Length; i++)
                info[i] = counters[i].NextValue();

            return info;
        }

        public static int CPUCoreCount()
        {
           int coreCount = 0;
                foreach (ManagementBaseObject item in new ManagementObjectSearcher("Select * from Win32_Processor").Get())
                {
                    if (int.TryParse(item["NumberOfCores"].ToString(), out int result))
                        coreCount += result;
                }
                return coreCount > 0 ? coreCount : Environment.ProcessorCount / 2;
        }


        private bool disposedValue;
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (counters != null && counters.Length > 0)
                    for (int i = counters.Length - 1; i >= 0; i--)
                        counters[i].Dispose();

                if (disposing)
                {
                    counters = null!;
                }

                // TODO: 释放未托管的资源(未托管的对象)并重写终结器
                // TODO: 将大型字段设置为 null
                disposedValue = true;
            }
        }

        // // TODO: 仅当“Dispose(bool disposing)”拥有用于释放未托管资源的代码时才替代终结器
        // ~CPUHelper()
        // {
        //     // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
        //     Dispose(disposing: false);
        // }

        public void Dispose()
        {
            // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
    }
}
